import { makeAutoObservable } from 'mobx';
import Http from '@/utils/http';
import { Toast } from 'antd-mobile';
import { history } from 'umi';
import { urlGet } from 'project-libs';
export default class UserStore {
  id: number = 0;
  username: string = '';
  avatar: string = '';
  phone: string | number = '';
  sign: string = '';
  constructor() {
    makeAutoObservable(this);
  }
  async getUserAsync(payload: any) {
    const user: any = await Http({
      url: '/user/detail',
      body: payload,
    });

    if (user) {
      const { id, username, avatar, phone, sign } = user;
      this.id = id;
      this.username = username;
      this.avatar = avatar;
      this.phone = phone;
      this.sign = sign;
    }
  }
  async editUserAsync(payload: any) {
    const result = await Http({
      url: '/user/edit',
      body: payload,
    });
    if (result) {
      Toast.success('编辑成功');
      history.push('/user');
    }
  }
  async loginAsync(payload: any) {
    const result: any = await Http({
      url: '/user/login',
      body: payload,
    });
    if (result) {
      localStorage.setItem('token', result.token);
      localStorage.setItem('username', result.username);
      
      urlGet('from') && history.push(urlGet('from'));
      Toast.success('登录成功');
    }
  }
  async registerAsync(payload: any) {
    const result: any = await Http({
      url: '/user/register',
      body: payload,
    });
    if (result) {
      localStorage.setItem('token', result.token);
      localStorage.setItem('username', result.username);
      Toast.success('注册成功');
    }
  }
  async logoutAsync(payload: any) {
    await Http({
      url: '/user/logout',
      body: payload,
    });
    Toast.success('退出登录成功');
    localStorage.clear();
    
    location.href = '/login?from=' + location.pathname;
  }
}
